package com.conan.dailyflickr.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;

import com.conan.dailyflickr.R;
import com.conan.dailyflickr.app.BitmapManager;
import com.conan.dailyflickr.app.DailyFlickrApplication;
import com.conan.dailyflickr.app.DailyPrefernces;
import com.conan.dailyflickr.app.DailyPrefernces.DailyInfo;
import com.conan.dailyflickr.app.PhotoDailyInfo;

public class DailyFlickrWidget extends AppWidgetProvider{

	private static final String TAG = "DailyFlickrWidget";
	private static String ACTION_WIDGET_CONTROL = "com.conan.imagemanager.WIDGET_CONTROL";
	private static final String URI_SCHEME 		= "flickr_widget";

	private static final String SETTING_COMMAND 				= "setting_command";

	private static final String REFRESH_NEXT_DAY_COMMAND 		= "refresh_next_day_command";
	private static final String REFRESH_PREV_DAY_COMMAND 		= "refresh_prev_day_command";
	private static final String REFRESH_NEXT_PHOTOS_COMMAND 	= "refresh_next_photos_command";
	private static final String REFRESH_PREV_PHOTOS_COMMAND 	= "refresh_prev_photos_command";

	private static final String REFRESH_MAIN_IMV_COMMAND 		= "refresh_main_imv_command#";
	public static final String ACTION_MAIN_IMV_COMMAND			= "ection_main_imv_command";
	
	public static final String STATUS 		= "Loading ...";
	public static int STORE_IMAGE 	= 0;
	public static int SET_WALLPAPER = 1;

	private int[] demos = {R.drawable.demo_0, R.drawable.demo_1, R.drawable.demo_2 };
	
	@Override
	public void onEnabled(Context context) {
		// This is only called once, regardless of the number of widgets of this type
		// We do not have any global initialization
		Log.i(TAG, "onEnabled()");
		super.onEnabled(context);
	}

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		

		if(appWidgetIds == null) {
			appWidgetIds = appWidgetManager.getAppWidgetIds(
					new ComponentName(context, DailyFlickrWidget.class));
		}
		
		if(!checkInternetConnection(context)) return;
		
		DailyInfo info = DailyPrefernces.getPref(context);

		Log.d(TAG, "onUpdate(): " + info._page);
		for(int appWidgetId : appWidgetIds) {
			
			Log.d(TAG, "onUpdate() ---- " + appWidgetId);
            // Get the layout for the App Widget and attach an on-click listener
            // to the button
            RemoteViews remoteView = new RemoteViews(context.getPackageName(), R.layout.flickr_widget);
            Random ran = new Random();
            remoteView.setImageViewResource(R.id.imv_main_img_of_dailyflickr_id, demos[ran.nextInt(demos.length)]);
            updateDisplayState(context, remoteView, appWidgetId);
            
            appWidgetManager.updateAppWidget(appWidgetId, remoteView);
    		
            
            // Tell the AppWidgetManager to perform an update on the current app widget
            // appWidgetManager.updateAppWidget(appWidgetId, remoteView);
            updateAppWidget(context, appWidgetId,  info, -1);

		}
	  
		super.onUpdate(context, appWidgetManager, appWidgetIds);
	}
	
	public static boolean checkInternetConnection(Context context){
		ConnectivityManager connMan = (ConnectivityManager) context
													.getSystemService(Context.CONNECTIVITY_SERVICE);

		return (connMan.getActiveNetworkInfo() != null 
				&& connMan.getActiveNetworkInfo().isConnected());
	}
	
	public static String buildDateString(Date date){
		SimpleDateFormat formatter = new SimpleDateFormat("d MMM yyyy");
	
		return formatter.format(date.getTime());	
	}
	
	private void updateDisplayState(Context context, RemoteViews remoteView, int appWidgetId) {
		Log.v(PhotoDailyInfo.TAG, "updateDisplayState: " + appWidgetId);
		
		// TODO set UI control event
		// setting button
		remoteView.setOnClickPendingIntent(
				R.id.bt_flickr_setting,
				makeControlPendingIntent(context, SETTING_COMMAND, appWidgetId));
		// next day button
		remoteView.setOnClickPendingIntent(
				R.id.bt_flickr_next_day_refresh,
				makeControlPendingIntent(context, REFRESH_NEXT_DAY_COMMAND, appWidgetId));
		// prev day button
		remoteView.setOnClickPendingIntent(
				R.id.bt_flickr_prev_day_refresh,
				makeControlPendingIntent(context, REFRESH_PREV_DAY_COMMAND, appWidgetId));
		// next photos button
		remoteView.setOnClickPendingIntent(
				R.id.bt_flickr_next_photos_refresh,
				makeControlPendingIntent(context, REFRESH_NEXT_PHOTOS_COMMAND, appWidgetId));
		// prev photos button
		remoteView.setOnClickPendingIntent(
				R.id.bt_flickr_prev_photos_refresh,
				makeControlPendingIntent(context, REFRESH_PREV_PHOTOS_COMMAND, appWidgetId));

		// Main image view
//		remoteView.setOnClickPendingIntent(
//				R.id.imv_main_img_of_dailyflickr_id,
//				makeControlPendingIntent(context, REFRESH_MAIN_IMV_COMMAND, appWidgetId));
		DailyInfo info = DailyPrefernces.getPref(context);
		remoteView.setTextViewText(R.id.tv_main_message_date_id,  buildDateString(info._date.getTime()));
	}

	private static PendingIntent makeControlPendingIntent(Context context, String command, int appWidgetId) {
		Intent active = new Intent();		
		active.setAction(ACTION_WIDGET_CONTROL);
		active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);		

		Uri data = Uri.withAppendedPath(
				Uri.parse(URI_SCHEME + "://widget/id/#" + command),
				String.valueOf(appWidgetId));
		
        active.setData(data);
		// active.putExtra(SETTING_COMMAND, command);
		Log.d(TAG, "makeControlPendingIntent --> " +  command);
		return(PendingIntent.getBroadcast(context, 0, active, PendingIntent.FLAG_UPDATE_CURRENT));
	}
	
	public static PendingIntent makeSelectPendingIntent(Context context, int position, int appWidgetId) {
		Intent active = new Intent();		
		active.setAction(ACTION_WIDGET_CONTROL);
		active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		active.putExtra("mainID", position);
		
		Uri data = Uri.withAppendedPath(
				Uri.parse(URI_SCHEME + "://widget/id/#" + REFRESH_MAIN_IMV_COMMAND + position),
				String.valueOf(appWidgetId));
        active.setData(data);

		return(PendingIntent.getBroadcast(context, 0, active, PendingIntent.FLAG_UPDATE_CURRENT));
	}
	
	public static PendingIntent makeMainSelectPendingIntent(Context context, int appWidgetId) {
		Intent active = new Intent();		
		active.setAction(ACTION_WIDGET_CONTROL);
		active.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		
		Uri data = Uri.withAppendedPath(
				Uri.parse(URI_SCHEME + "://widget/id/#" + ACTION_MAIN_IMV_COMMAND),
				String.valueOf(appWidgetId));
        active.setData(data);

		return(PendingIntent.getBroadcast(context, 0, active, PendingIntent.FLAG_UPDATE_CURRENT));
	
	}

	private  void updateAppWidget(Context context, int appWidgetId, DailyInfo info, int id){
		
		Log.d(PhotoDailyInfo.TAG, "updateAppWidget --> startService" +  info._page + " - " +  info._date);
		// store pref
		DailyPrefernces.putPref(context, info._page, info._date);
		
		Intent intent = new Intent(context, UpdateService.class);
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		intent.putExtra(DailyPrefernces.PREFS_NAME_PAGE, info._page);
		intent.putExtra(DailyPrefernces.PREFS_NAME_MAIN_ID, id);
		context.startService(intent);
		Log.d(PhotoDailyInfo.TAG, "updateAppWidget --> startService" +  info._page + " - " + id + " - " );
		
	}
	
	private  void updateDayAppWidget(Context context, int appWidgetId, String action, DailyInfo info){
		info._page = 1;
		if (action.equalsIgnoreCase(REFRESH_NEXT_DAY_COMMAND)) {
			info._date.add(Calendar.DATE, 1);
			// check is now
			
		} else  if (action.equalsIgnoreCase(REFRESH_PREV_DAY_COMMAND)) {
			info._date.add(Calendar.DATE, -1);
		}
		
		updateAppWidget( context, appWidgetId, info, -1);
	}	
	
	private  void downloadImage(final Context context, int appWidgetId, boolean setWallpaper){
        /*RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.flickr_widget);
        updateViews.setTextViewText(R.id.tv_main_message_text_id, "Downloading ...");
        
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        manager.updateAppWidget(appWidgetId, updateViews);*/
        
//		Intent intent = new Intent(context, UpdateService.class);
//		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
//		intent.putExtra(DailyPrefernces.PREFS_NAME_URL, true);
//		intent.putExtra(DailyPrefernces.PREFS_NAME_SET_WALLPAPER, setWallpaper);
//		context.startService(intent);
		
		Thread thread = new Thread() {
            @Override
            public void run() {
               DailyInfo info = DailyPrefernces.getPref(context);
               if(!TextUtils.isEmpty(info._url)){
            	   boolean rs = BitmapManager.downloadBitmap(context, info._url, info._title, false);
               }
            }
        };
        thread.start();
	}

	private void stopService(Context context){    	
		Intent intent = new Intent(context, UpdateService.class);		
		intent.putExtra("stop", true);
		context.startService(intent);
		Log.d(TAG, "updateAppWidget --> stopService" );
	}


	@Override
	public void onReceive(Context context, Intent intent) {
		final String action = intent.getAction();
		if (TextUtils.isEmpty(action))
			return;

		Log.d(TAG, "OnReceive:Action: " + action);
		if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
			final int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			stopService(context);
			
			this.onDeleted(context, new int[] { appWidgetId });
			
		} if(ACTION_WIDGET_CONTROL.equals(action)){
			int appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			
			onHandleAction(context,  intent.getData(), appWidgetId);				
		}
		super.onReceive(context, intent);
	}

	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		Log.d(TAG, "onDelete()");
		for (int appWidgetId : appWidgetIds) {
			Log.d(TAG, "Removing preference for id " + appWidgetId);			
		}
		stopService(context);
		
		super.onDeleted(context, appWidgetIds);
	}

	@Override
	public void onDisabled(Context context) {
		stopService(context);
		super.onDisabled(context);
	}

	public void onHandleAction(Context context, Uri data, int appWidgetId) {
		// TODO handle our action
	   final String action = data.getFragment();
        if (TextUtils.isEmpty(action)) {
                return;
        }
        
        DailyInfo info = DailyPrefernces.getPref(context);
		if (action.equalsIgnoreCase(SETTING_COMMAND)) {
			Intent mIntent = new Intent(context, DowloadedPhotos.class);
			mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_HISTORY|Intent.FLAG_ACTIVITY_NO_ANIMATION);
			context.startActivity(mIntent);
		} else if (action.equalsIgnoreCase(REFRESH_NEXT_DAY_COMMAND)) {
			DailyFlickrApplication.makeToastMessage(STATUS + " next day");
			updateDayAppWidget(context, appWidgetId ,REFRESH_NEXT_DAY_COMMAND  , info);
		} else  if (action.equalsIgnoreCase(REFRESH_PREV_DAY_COMMAND)) {
			DailyFlickrApplication.makeToastMessage(STATUS + " prev day");
			updateDayAppWidget(context, appWidgetId , REFRESH_PREV_DAY_COMMAND , info);			
		} else if (action.equalsIgnoreCase(REFRESH_NEXT_PHOTOS_COMMAND)) {
			DailyFlickrApplication.makeToastMessage(STATUS + " next page");
			info._page = info._page + 1; 
			updateAppWidget(context, appWidgetId , info, -1);
		} else if (action.equalsIgnoreCase(REFRESH_PREV_PHOTOS_COMMAND)) {
			DailyFlickrApplication.makeToastMessage(STATUS + " prev page");
			info._page = info._page - 1;
			if(info._page < 1) {
				info._page = 33;
				info._date.add(Calendar.DATE, -1);
			}
			updateAppWidget(context, appWidgetId , info, -1);
		} else if (action.contains(REFRESH_MAIN_IMV_COMMAND)) {			
			DailyFlickrApplication.makeToastMessage(STATUS + " new photo");
            
			String[] actions = action.split("#");
			int position = Integer.parseInt(actions[1]);			
			updateAppWidget(context, appWidgetId , info , position);			
		} else if (action.contains(ACTION_MAIN_IMV_COMMAND)) {			
			DailyFlickrApplication.makeToastMessage("downloading");
					
			Intent intent = new Intent(context, DailyImageDialog.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_NO_HISTORY|Intent.FLAG_ACTIVITY_NO_ANIMATION);
			intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
			// intent.putExtra(DailyPrefernces.PREFS_NAME_SET_WALLPAPER, false);
			context.startActivity(intent);			
			// downloadImage(context, appWidgetId, false);			
		}
	
	}
}
